using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System.Security.Claims;
using System.Text.Json;

namespace HtERP.Services
{
    public class PersistingAuthenticationStateProvider : AuthenticationStateProvider
    {
        private readonly ILogger _logger;
        private readonly ProtectedLocalStorage _localStorage;
        private Task<AuthenticationState> _currentAuthenticationState;
        private const string AuthStateKey = "AuthState";
        private const string AuthTokenKey = "AuthToken";
        
        // 静态实例引用，用于在无法依赖注入时访问
        private static PersistingAuthenticationStateProvider? _instance;
        
        public PersistingAuthenticationStateProvider(ILogger logger, 
            ProtectedLocalStorage localStorage)
        {
            _logger = logger;
            _localStorage = localStorage;
            _instance = this; // 保存实例引用
            
            // 初始化认证状态，尝试从本地存储恢复
            _currentAuthenticationState = LoadAuthenticationStateFromStorageAsync();
        }

        private async Task<AuthenticationState> LoadAuthenticationStateFromStorageAsync()
        {
            try
            {
                _logger.Log(LogLevel.Info, "尝试从本地存储加载认证状态");
                var storedState = await _localStorage.GetAsync<string>(AuthStateKey);
                
                if (!string.IsNullOrEmpty(storedState.Value))
                {
                    // 解析存储的用户信息
                    var userInfo = JsonSerializer.Deserialize<UserInfo>(storedState.Value);
                    if (userInfo != null)
                    {
                        // 重建ClaimsIdentity
                        var claims = new List<Claim>
                        {
                            new Claim(ClaimTypes.Name, userInfo.Username),
                            new Claim(ClaimTypes.Role, userInfo.Role)
                        };
                        
                        if (!string.IsNullOrEmpty(userInfo.UserId))
                        {
                            claims.Add(new Claim(ClaimTypes.NameIdentifier, userInfo.UserId));
                        }
                        
                        var identity = new ClaimsIdentity(claims, "custom");
                        var user = new ClaimsPrincipal(identity);
                        _logger.Log(LogLevel.Info, $"成功从本地存储恢复认证状态: {userInfo.Username}");
                        return new AuthenticationState(user);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, "从本地存储加载认证状态失败: " + ex.Message);
            }
            
            // 如果无法恢复，初始化为未认证状态
            var emptyIdentity = new ClaimsIdentity();
            var emptyUser = new ClaimsPrincipal(emptyIdentity);
            return new AuthenticationState(emptyUser);
        }

        public override Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            _logger.Log(LogLevel.Info, "获取认证状态");
            return _currentAuthenticationState;
        }
        
        // 增强的设置认证状态方法，接受更多用户信息
        public async Task SetAuthenticationStateAsync(string username, string? userId = null, string role = "User")
        {
            _logger.Log(LogLevel.Info, $"设置认证状态: 用户名={username}, 角色={role}");
            
            // 创建必要的Claim
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.Role, role)
            };
            
            // 如果提供了用户ID，也添加到Claim中
            if (!string.IsNullOrEmpty(userId))
            {
                claims.Add(new Claim(ClaimTypes.NameIdentifier, userId));
            }
            
            var identity = new ClaimsIdentity(claims, "custom");
            var user = new ClaimsPrincipal(identity);
            
            // 保存到本地存储
            try
            {
                var userInfo = new UserInfo { Username = username, UserId = userId, Role = role };
                var json = JsonSerializer.Serialize(userInfo);
                await _localStorage.SetAsync(AuthStateKey, json);
                _logger.Log(LogLevel.Info, "认证状态已保存到本地存储");
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, "保存认证状态到本地存储失败: " + ex.Message);
            }
            
            _currentAuthenticationState = Task.FromResult(new AuthenticationState(user));
            NotifyAuthenticationStateChanged(_currentAuthenticationState);
        }

        // 用于清除认证状态
        public async Task ClearAuthenticationStateAsync()
        {
            _logger.Log(LogLevel.Info, "清除认证状态");
            
            // 清除本地存储
            try
            {
                await _localStorage.DeleteAsync(AuthStateKey);
                _logger.Log(LogLevel.Info, "已清除本地存储中的认证状态");
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, "清除本地存储中的认证状态失败: " + ex.Message);
            }
            
            var identity = new ClaimsIdentity();
            var user = new ClaimsPrincipal(identity);
            _currentAuthenticationState = Task.FromResult(new AuthenticationState(user));
            NotifyAuthenticationStateChanged(_currentAuthenticationState);
        }
        
        // 静态方法，用于在无法获取实例时设置认证状态
        public static void SetGlobalAuthenticationState(string username, string? userId = null, string role = "User")
        {
            if (_instance != null)
            {
                _instance.SetAuthenticationStateAsync(username, userId, role).ConfigureAwait(false);
            }
            else
            {
                // 如果实例不存在，记录警告日志
                Console.WriteLine("警告: PersistingAuthenticationStateProvider实例不存在，无法设置认证状态");
            }
        }
        
        // 用于存储用户信息的辅助类
        private class UserInfo
        {
            public string Username { get; set; } = string.Empty;
            public string? UserId { get; set; }
            public string Role { get; set; } = "User";
        }
    }
}